#include "qgetversion.h"

#include <QDateTime>
#include <QFile>
#include <QApplication>

QGetVersion::QGetVersion(QObject *parent) :
    QObject(parent),
    m_reply(NULL),
    m_timer(new QTimer(this))
{
    connect(m_timer,SIGNAL(timeout()),this,SLOT(timer()));
}

QGetVersion::~QGetVersion()
{
    stop();
}

bool QGetVersion::start(const QUrl &url)
{
    if(m_reply!=NULL)
    {
        return false;
    }
    m_reply = m_manager.get(QNetworkRequest(url));

    connect(m_reply, SIGNAL(finished()),
            this, SLOT(finished()));
    connect(m_reply, SIGNAL(readyRead()),
            this, SLOT(readyRead()));

    m_last_time=QDateTime::currentDateTime();
    m_timer->start(100);
    return true;
}

void QGetVersion::finished()
{
    QFile f(qApp->applicationDirPath()+"/update.txt");
    f.open(QFile::ReadOnly);
    m_data=f.readAll();
    f.close();
    emit finish(m_data);
    stop();
}

void QGetVersion::readyRead()
{
    m_data=m_reply->readAll();
    m_last_time=QDateTime::currentDateTime();
}

void QGetVersion::timer()
{
    if(m_last_time.msecsTo(QDateTime::currentDateTime())>5000)
    {
        stop();
        emit offline();
    }
}

void QGetVersion::stop()
{
    if(m_reply!=NULL)
    {
        m_reply->abort();
        m_reply=NULL;
    }
    m_data=QByteArray();
    m_timer->stop();
}
